package com.zlh123.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlh123.commom.util.PageResult;
import com.zlh123.entity.Book;
import com.zlh123.entity.BorrowRecord;
import com.zlh123.entity.User;
import com.zlh123.mapper.BorrowRecordMapper;
import com.zlh123.service.IBookService;
import com.zlh123.service.IBorrowRecordService;
import com.zlh123.service.IUserService;
import com.zlh123.vo.RecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zlh
 * @since 2025-01-13
 */
@Service
public class BorrowRecordServiceImpl extends ServiceImpl<BorrowRecordMapper, BorrowRecord> implements IBorrowRecordService {
   @Autowired
   private IBookService bookService;
   @Autowired
   private IUserService userService;
   @Override
   public PageResult<BorrowRecord> findRecordsByPage(int page, int pageSize) {
       //开始分页
       Page<BorrowRecord> page1=this.page(new Page<>(page, pageSize));
        //分页结果
       return new PageResult<>(page1.getRecords(),page1.getTotal());
    }
   //条件查询
   @Override
   public PageResult<BorrowRecord> search(int page, int pageSize, RecordVo recordVo) {
       QueryWrapper<BorrowRecord> wrapper = new QueryWrapper<>();
       wrapper.like(StrUtil.isNotBlank(recordVo.getUname()), "uname", recordVo.getUname())
               .like(StrUtil.isNotBlank(recordVo.getName()), "name", recordVo.getName())
               .like(StrUtil.isNotBlank(recordVo.getBname()), "bname", recordVo.getBname());
       // 开始分页查询
       Page<BorrowRecord> pageResult = this.page(new Page<>(page, pageSize), wrapper);
       // 获取所有借阅记录中的书籍ID列表
       List<Integer> bookIds = pageResult.getRecords().stream()
               .map(BorrowRecord::getBid)
               .collect(Collectors.toList());
       // 根据书籍ID列表批量获取书籍信息
       Map<Integer, String> bookIdToNameMap = bookService.listByIds(bookIds).stream()
               .collect(Collectors.toMap(Book::getBid, Book::getBname));
       // 处理用户名、姓名和书籍名称
       pageResult.getRecords().forEach(record -> {
           User user = userService.getById(record.getUid());
           if (user != null) {
               record.setUname(user.getUname());
               record.setName(user.getName());
           }
           // 设置书籍名称
           if (bookIdToNameMap.containsKey(record.getBid())) {
               record.setBname(bookIdToNameMap.get(record.getBid()));
           }
       });
       // 封装分页结果
       return new PageResult<>(pageResult.getRecords(), pageResult.getTotal());
   }

}
